import router from '@/router';
import { UserInfo } from '@/utils/interface';
import { store } from '..';

const useUserInfo = defineStore('user-info', {
  state: () => ({
    userInfo: {
      class_name: '',
      key: 0,
      major_name: '',
      username: '',
    },
    token: '',
    test_id: 0,
  }),
  actions: {
    logOut() {
      this.$patch({
        userInfo: {
          class_name: '',
          key: 0,
          major_name: '',
          username: '',
        },
        token: '',
      });
      router.replace('/login');
    },
    setToken(token: string) {
      this.$patch({ token });
    },
    setUserInfo(data: UserInfo) {
      this.$patch({
        userInfo: data,
      });
    },
    setTestId(test_id: number) {
      this.$patch({ test_id });
    },
  },
  getters: {
    getUserName(state) {
      return state.userInfo.username;
    },
    getUserId(state) {
      return state.userInfo.key;
    },
    getToken(state) {
      return state.token;
    },
    getClassName(state) {
      return state.userInfo.class_name;
    },
    getTestId(state) {
      return state.test_id;
    },
  },
  persist: {
    enabled: true,
    //数组方式，可以储存多个对,默认为会话存储
    strategies: [
      {
        //更改为本地存储
        storage: localStorage,
        //选择哪些state中的状态持久化
        paths: ['userInfo', 'token', 'test_id'],
      },
    ],
  },
});

export function useUserInfoStoreWithOut() {
  return useUserInfo(store);
}
